import axios from 'axios';
import BASE_CONFIG from './config';
import { conlogText,ErrConlog } from '@/utils/function';
import { colorArr } from '@/utils/constant';
import type { AxiosInstance } from 'axios';
import type { IResponse } from '../type/interface';
// %c
import settle from 'axios/lib/core/settle';
import buildURL from 'axios/lib/helpers/buildURL';
import buildFullPath from 'axios/lib/core/buildFullPath';
const color = colorArr[Math.round(Math.random())];
//定义模板全局变量
const axiosInstance: AxiosInstance = axios.create({
	baseURL: BASE_CONFIG.BASE_URL,
	timeout: 100000,
});
// 请求拦截
axiosInstance.interceptors.request.use(
	(response: IResponse | any) => {
		if (uni.getStorageSync('TOKEN')) {
			response.headers['Authorization'] = 'Bearer ' + uni.getStorageSync('TOKEN');
		}
		conlogText(`---【开始】【服务器请求】【 ${response.baseURL} 】【 ${response.url} 】---`,'',color);
		conlogText('【请求头】',response.headers);
		conlogText('【请求参数】',response.data);
		conlogText('【请求方法】',response.method);
		return response;
	},
	(error: Error) => {
		ErrConlog(error);
		return Promise.reject(error);
	}
);
// 响应拦截
axiosInstance.interceptors.response.use(
	(response: IResponse | any) => {
		conlogText('【返回数据】',response.data);
		conlogText(`---【结束】【服务器请求】【 ${response.config.baseURL} 】【 ${response.config.url} 】---`,'',color);
		return Promise.resolve(response.data);
	},
	(error: Error) => {
		ErrConlog(error);
		return Promise.reject(error);
	}
);

axios.defaults.adapter = (config: any) => {
	return new Promise((resolve, reject) => {
		const fullurl = buildFullPath(config.baseURL, config.url);
		uni.request({
			method: config.method.toUpperCase(),
			url: buildURL(fullurl, config.params, config.paramsSerializer),
			header: config.headers,
			data: config.data || config.params,
			dataType: config.dataType,
			responseType: config.responseType,
			sslVerify: config.sslVerify,
			complete(response: IResponse | any) {
				response = {
					data: response.data,
					status: response.statusCode,
					errMsg: response.errMsg,
					header: response.header,
					config,
				};
				settle(resolve, reject, response);
			},
		});
	});
};
export default axiosInstance;
